package com.gzhryc.shared_device.oem.h5.mng.controllers.sys;

import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.secruity.EncryptTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.system.ManagerService;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 后台管理员自管理页面接口
 * @author 张浩
 * @version 2016-9-19
 */
public class ManagerSelfController {

	@Route(value="/sys/manager/self/info.html",method="get")
	public String update(HttpServletRequest request,HttpSession session){
		Manager loginManager = WebUtils.getAttribute(session,SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
		WebUtils.setAttribute(request,loginManager);
		return "/sys/info.html";
	}

	/**
	 * 访问修改密码页面
	 * @param request
	 * @return
	 */
	@Route(value="/sys/manager/self/updatePwd.html",method="get")
	public String updatePwd(HttpServletRequest request){
		return "/sys/pwd.html";
	}

	@Route(value="/sys/manager/self/updatePwd.do",method="post")
	public AjaxResult doUpdatePwd(HttpServletRequest request, HttpSession session){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改密码失败");
		try {
			String oldPassword = WebUtils.getString(request,"oldPassword");
			String password = WebUtils.getString(request,"password");
			if(StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(password)) {
				Manager loginManager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
				if(loginManager.getLoginPwd().equals(EncryptTools.md5(oldPassword))){
					Manager manager = new Manager();
					manager.setId(loginManager.getId());
					manager.setLoginPwd(EncryptTools.md5(password));
					if(ManagerService.self().updateInfo(manager)){
						loginManager = ManagerService.self().getById(manager.getId());
						session.setAttribute(SysConstants.SESSION_LOGIN_MANAGER, loginManager);
						result.setCode(DtoConstants.SUCCESS,null);
					}
				}else {
					result.setMsg("旧密码错误！");
				}
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
}
